import { createRouter, createWebHistory } from 'vue-router'
import { useAuthStore } from '../stores/auth'
import MobileManusChat from '../views/MobileManusChat.vue'
import MarkdownTest from '../views/MarkdownTest.vue'

const routes = [
  {
    path: '/',
    redirect: '/login'
  },
  {
    path: '/login',
    name: 'Login',
    component: () => import('../views/Login.vue')
  },
  {
    path: '/register',
    name: 'Register',
    component: () => import('../views/Register.vue')
  },
  {
    path: '/home',
    name: 'Home',
    component: () => import('../views/Home.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/love-chat',
    name: 'LoveChat',
    component: () => import('../views/LoveChat.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/manus-chat',
    name: 'ManusChat',
    component: () => import('../views/ManusChat.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/mobile-home',
    name: 'MobileHome',
    component: () => import('../views/MobileHome.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/mobile-love-chat',
    name: 'MobileLoveChat',
    component: () => import('../views/MobileLoveChat.vue'),
    meta: { requiresAuth: true }
  },
  {
    path: '/mobile-manus-chat',
    name: 'MobileManusChat',
    component: MobileManusChat,
    meta: { requiresAuth: true }
  },
  {
    path: '/markdown-test',
    name: 'MarkdownTest',
    component: MarkdownTest
  }
]

const router = createRouter({
  history: createWebHistory(),
  routes
})

// 路由守卫
router.beforeEach((to, from, next) => {
  const authStore = useAuthStore()
  const isMobile = window.innerWidth <= 768
  
  // 移动端和桌面端页面映射
  const mobilePageMap = {
    '/home': '/mobile-home',
    '/love-chat': '/mobile-love-chat',
    '/manus-chat': '/mobile-manus-chat'
  }
  
  const desktopPageMap = {
    '/mobile-home': '/home',
    '/mobile-love-chat': '/love-chat',
    '/mobile-manus-chat': '/manus-chat'
  }
  
  // 检查是否需要重定向到对应端的页面
  if (isMobile && mobilePageMap[to.path]) {
    // 移动端访问桌面端页面，重定向到移动端
    next(mobilePageMap[to.path])
    return
  } else if (!isMobile && desktopPageMap[to.path]) {
    // 桌面端访问移动端页面，重定向到桌面端
    next(desktopPageMap[to.path])
    return
  }
  
  // 认证检查
  if (to.meta.requiresAuth && !authStore.isAuthenticated) {
    next('/login')
  } else if (to.path === '/login' && authStore.isAuthenticated) {
    // 登录后根据屏幕大小跳转
    if (isMobile) {
      next('/mobile-home')
    } else {
      next('/home')
    }
  } else {
    next()
  }
})

export default router 